<?php

declare (strict_types=1);

namespace app\controller\auth;

use app\BaseController;
use think\facade\View;

class Role extends BaseController
{
    //当前登录管理员所有子组别
    protected $childrenGroupIds = [];

    //当前组别列表数据
    protected $groupData = [];

    public function initialize()
    {
        parent::initialize();

        $model = new \app\model\auth\Role();
        $this->childrenGroupIds = auth()->getChildrenGroupIds(true);
        $groupList = $model->getAuthGroupList($this->childrenGroupIds);
        tree()->init($groupList);
        $result = [];
        if (auth()->isSuperAdmin()) {
            $result = tree()->getTreeList(tree()->getTreeArray(0));
        } else {
            $groups = auth()->getGroups();
            foreach ($groups as $m => $n) {
                $result = array_merge($result, tree()->getTreeList(tree()->getTreeArray($n['pid'])));
            }
        }
        $groupName = [];
        foreach ($result as $k => $v) {
            $groupName[$v['id']] = $v['name'];
        }
        $this->groupData = $groupName;

        return View::assign('groupData', $this->groupData);
    }

    /**
     * 主页
     *
     * @return mixed
     */
    public function index()
    {
        if ($this->request->isAjax()) {
            $model = new \app\model\auth\Role();
            $list = $model->getAuthGroupAll($this->groupData);
            $groupList = [];
            foreach ($list as $k => $v) {
                $groupList[$v['id']] = $v;
            }
            $list = [];
            foreach ($this->groupData as $k => $v) {
                if (isset($groupList[$k])) {
                    $groupList[$k]['name'] = $v;
                    $list[] = $groupList[$k];
                }
            }

            return json(result()->success(['count' => count($list), 'rows' => $list]));
        }

        return view();
    }

    /**
     * 新增角色
     *
     * @return \think\response\View
     */
    public function add()
    {
        if ($this->request->isPost()) {
            $addRole = $this->request->post('row/a', [], 'strip_tags');
            // 判断新增角色
            $validate = $this->validate($addRole, 'auth/Role.addRole');
            if (true !== $validate) {
                return json(result()->fail($validate));
            }
        }

        return View::fetch('add');
    }
}